{ "metadata": { "name": "Intro to Python" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Introduction to Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This IPython notebook provides an introduction into some of the basics of python and the coding idioms of Python. We will start by reviewing the different types of data that can be stored in Python and proceed to other topics from there. While you work through this notebook it would be wise to either be playing with the code in the notebook itself or in a ipython console that you open on your own. I will provide some comments intended for the reader that are denoted by a # in Python. Remember that while you are learning Python and even once you master Python that Google will be your best friend. If you ever have a question about how to do something then you will almost certainly be able to find an answer online. Following the information in this notebook, there will be several problems that you will be asked to turn in." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Types of Data in Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This section will introduce you to several different types of data that you will frequently use in Python. We will touch on strings, integers, floats, and lists (Note: There are complex numbers as well, but they are very similar to floats and I also suggest learning a little about sets and dictionaries). Each of these will have different uses and you will need them to complete future labs. As a note prior to beginning. In python, x = ___ , denotes x as whatever fills in the blank space after the equal sign. This is known as being an identifier. You can use whatever variable/word you want with the exeception of beginning your identifier with a number and for several words that python has claimed for itself (and, del, from, not, while, as, elif, global, or, with, assert, else, if, pass, break, except, import, print, class, exec, in, raise, continue, finally, is, return, def, for, lambda, try). Below we define num as an identifier for the object 1. Notice when we tell python to print the identifier num that it returns 1. Another important to note is that python begins indexing at element 0. If you want the first element from a list or string then it will be denoted as the 0th element." ] }, { "cell_type": "code", "collapsed": false, "input": [ "num = 1\n", "print(num) # This will return what num is tied to (1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1\n" ] } ], "prompt_number": 23 }, { "cell_type": "code", "collapsed": false, "input": [ "testlist = [0, 1, 2, 3, 4]\n", "print(testlist[0]) # Notice this gives us the first element of testlist." ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0\n" ] } ], "prompt_number": 24 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings are a list of characters(includes numbers and symbols) in a certain order. These are declared in python by using quotation marks (', \", or \"\"\"). Notice below that when we ask python to print what type 'hello' is that it returns type str. This is letting us know that 'hello' is a string." ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(type('hello'))\n", "'hello'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] }, { "output_type": "pyout", "prompt_number": 3, "text": [ "'hello'" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are several operations that can be done to strings. Typically strings are useful for printing updates or information from the code, but they can be used for other things as well (such as creating urls to direct python to). For example, when printing, you can print multiple lines within one print statement by using \\n. You can also concatenate(add). Look at the difference between the examples below." ] }, { "cell_type": "code", "collapsed": false, "input": [ "str1 = 'welcome'\n", "str2 = 'to'\n", "str3 = 'bootcamp'\n", "print(str1 + str2 + str3) # Here we just print the strings concatenated together" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "welcometobootcamp\n" ] } ], "prompt_number": 27 }, { "cell_type": "code", "collapsed": false, "input": [ "print(str1 + ' \\n'+str2 + ' \\n'+str3)# Here we concatenate&printthe strings and add \\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "welcome \n", "to \n", "bootcamp\n" ] } ], "prompt_number": 29 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also slice(pull specific elements from) strings. Look at the examples below (The %s is a place holder for what comes after %) :" ] }, { "cell_type": "code", "collapsed": false, "input": [ "practicestr = 'abcdefghi'\n", "print('first element of practicestr is \"%s\"' % practicestr[0])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "first element of practicestr is \"a\"\n" ] } ], "prompt_number": 36 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also access a range of elements from strings in the following way." ] }, { "cell_type": "code", "collapsed": false, "input": [ "pracstr = 'abcdefghi'\n", "print(pracstr[0:]) # The : means everything afterwards. This will print whole string.\n", "print(pracstr[5:]) # This will print from element 5 on" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "abcdefghi\n", "fghi\n" ] } ], "prompt_number": 39 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now see what the command [::-1] does after the string." ] }, { "cell_type": "code", "collapsed": false, "input": [ "pracstr = 'abcdefghi'\n", "# Write your practice command here" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 41 }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are other things that you can do with strings, but this should suffice for now. A couple of the other cool things are included below (The actual command is after the %). If you want more instruction on any of these, ask questions." ] }, { "cell_type": "code", "collapsed": false, "input": [ "string = 'thisisasentencestring'\n", "capitallets = 'ABCDEFGH'\n", "print('number of a\\'s in string = %s') %string.count('a')\n", "print('string in all upper case is %s') %string.upper()\n", "print('capitallets in all lower case is %s') %capitallets.lower()\n", "print('replace D in capitallets with another A is %s') %capitallets.replace('D', 'A')\n", "print('a is in the %s element of string') %string.find\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "number of a's in string = 1\n", "string in all upper case is THISISASENTENCESTRING\n", "capitallets in all lower case is abcdefgh\n", "replace D in capitallets with another A is ABCAEFGH\n" ] } ], "prompt_number": 73 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Integers and Floats" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Integers are exactly what they sound like. Integers are all positive and negative integers; for you math folk it is $\\mathbb{Z}$. Floats are all of the real numbers, $\\mathbb{R}$. It is important to note the difference in programming between integers and floats because their operations will do different things. To declare a number as a float, you either need to tell the computer it is a float via command or add a decimal place. See below:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "type(1) # Just a normal integer will be recorded as an integer" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 46, "text": [ "int" ] } ], "prompt_number": 46 }, { "cell_type": "code", "collapsed": false, "input": [ "type(1.0) # Just adding a decimal place is the easiest way to declare a float" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 45, "text": [ "float" ] } ], "prompt_number": 45 }, { "cell_type": "code", "collapsed": false, "input": [ "type(float(1)) # but you can tell python that something is a float." ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 47, "text": [ "float" ] } ], "prompt_number": 47 }, { "cell_type": "code", "collapsed": false, "input": [ "print(int(5.5))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "5\n" ] } ], "prompt_number": 63 }, { "cell_type": "code", "collapsed": false, "input": [ "print(float(5))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "5.0\n" ] } ], "prompt_number": 64 }, { "cell_type": "markdown", "metadata": {}, "source": [ "I told you that they were going to be a little different so let me show you the difference. We obviously know that 2/4 should be equal to .5, but lets see what happens when we try it with integers." ] }, { "cell_type": "code", "collapsed": false, "input": [ "2/4" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 48, "text": [ "0" ] } ], "prompt_number": 48 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Integer division gave us 0 for 2/4. This is the wrong answer. The explanation is actually pretty simple. The division algorithm says: $\\text{Let } a,b \\text{ be integers with } b>0 \\text{ then there exist unique integers } q \\text{ and } r \\text{ such that }$\n", "\n", "$a=bq +r \\text{ and } 0 \\leq r < b $\n", "\n", "Note that r is actually the remainder. Integer division simply returns the q from this equation.\n", "\n", "Now if we do this division in floats, we will get the answer that we are looking for." ] }, { "cell_type": "code", "collapsed": false, "input": [ "2.0/4.0" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 49, "text": [ "0.5" ] } ], "prompt_number": 49 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Integer operations certainly have their place, but typically you will want to be using float division. If at least one of the numbers is a float then the output will be returned as a float. There is also a small cheat you can put at the beginning of your file that will declare all of your division as float division for your whole script. That cheat is to write from \\__future\\__ import division at the beginning of your script. That will make all division float division." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from __future__ import division\n", "4/3" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 54, "text": [ "1.3333333333333333" ] } ], "prompt_number": 54 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The rest of the operations should work pretty similarly between the two, but it is always better to be safe and work with floats if you want to be in the real numbers. Another operation that tends to be very useful is modulus. You do modulus with %. The modulus will return the r from the division algorithm. This will be useful in many instances. For example, if you need to know whether a number is even or odd then you can check the number modulus 2." ] }, { "cell_type": "code", "collapsed": false, "input": [ "4%2 # gives us 0 so 2 must divide evenly into 4" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 57, "text": [ "0" ] } ], "prompt_number": 57 }, { "cell_type": "code", "collapsed": false, "input": [ "5%2 # gives us 1 so 2 doesn't divide evenly into 5" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 58, "text": [ "1" ] } ], "prompt_number": 58 }, { "cell_type": "code", "collapsed": false, "input": [ "1436213623%2 # gives us 1 so 2 doesn't divide evenly into that number" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 59, "text": [ "1" ] } ], "prompt_number": 59 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In many programming languages the exponent is denoted as ^, but this is not true in python. If you want to take something to a power then you need to use **. See below:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "3**2" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 60, "text": [ "9" ] } ], "prompt_number": 60 }, { "cell_type": "code", "collapsed": false, "input": [ "11**4" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 61, "text": [ "14641" ] } ], "prompt_number": 61 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists are extremely useful for keeping track of information. A list can contain floats, integers, strings or any combination of them. A list is declared by using the square brackets, []. You can append/remove new items to/from a list." ] }, { "cell_type": "code", "collapsed": false, "input": [ "practicelist = [1, 2, 3, 4]\n", "practicelist" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 90, "text": [ "[1, 2, 3, 4]" ] } ], "prompt_number": 90 }, { "cell_type": "code", "collapsed": false, "input": [ "practicelist.append(5) # append 5 to our list\n", "practicelist" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 91, "text": [ "[1, 2, 3, 4, 5]" ] } ], "prompt_number": 91 }, { "cell_type": "code", "collapsed": false, "input": [ "practicelist.remove(1) # remove 1 from our list\n", "practicelist" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 92, "text": [ "[2, 3, 4, 5]" ] } ], "prompt_number": 92 }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also replace elements within a list." ] }, { "cell_type": "code", "collapsed": false, "input": [ "anotherlist = ['a', 2, 3, 4]\n", "print('this is the first element of another list', anotherlist[0])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('this is the first element of another list', 'a')\n" ] } ], "prompt_number": 95 }, { "cell_type": "code", "collapsed": false, "input": [ "anotherlist[0] = 1\n", "print('now this is the first element of another list', anotherlist[0])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('now this is the first element of another list', 1)\n" ] } ], "prompt_number": 97 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Taking slices of lists works the same way as taking slices of strings." ] }, { "cell_type": "code", "collapsed": false, "input": [ "list1 = [1, 2, 3, 4, 5, 6, 7]\n", "list1[2:5] # take elements 2 through 5" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 99, "text": [ "[3, 4, 5]" ] } ], "prompt_number": 99 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also concatenate lists just like we did with strings." ] }, { "cell_type": "code", "collapsed": false, "input": [ "list1 = [1, 2]\n", "list2 = ['a', 'b']\n", "list1 + list2" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 93, "text": [ "[1, 2, 'a', 'b']" ] } ], "prompt_number": 93 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In addition to being able to do these things that you were able to do in a string, lists allow you to find the max and min (among other things) within the list." ] }, { "cell_type": "code", "collapsed": false, "input": [ "list1 = [1, 2, 36, 256, 2562, 56]\n", "print('The max is %s' %max(list1))\n", "print('The min is %s' %min(list1))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The max is 2562\n", "The min is 1\n" ] } ], "prompt_number": 108 }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the built in commands to build lists is with the range command. Below we will build a list of numbers from 0 to 9 using range in several different ways." ] }, { "cell_type": "code", "collapsed": false, "input": [ "range(10) # if you just input an integer it will build up until that number" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 100, "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" ] } ], "prompt_number": 100 }, { "cell_type": "code", "collapsed": false, "input": [ "range(0,10,1) # you can tell it to start at 0 and go to 10 taking 1 unit steps" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 101, "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" ] } ], "prompt_number": 101 }, { "cell_type": "code", "collapsed": false, "input": [ "range(1,10) # we can go from 1 to 9 as well by specifying to start at 1" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 102, "text": [ "[1, 2, 3, 4, 5, 6, 7, 8, 9]" ] } ], "prompt_number": 102 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Conditionals, Loops, and Booleans" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conditional statements, loops, and booleans permit a programmer increased flexibility. These permit you to give your computer specific commands that save you a lot of coding. For example, if you want to remove all of the even numbers from a list then you can say something like below:\n", "\n", "Also some symbols that will be useful:\n", "\n", "< less than\n", "\n", "> greater than\n", "\n", "<= less than or equal\n", "\n", ">= greater than or equal\n", "\n", "!= not equal\n", "\n", "== equal to" ] }, { "cell_type": "code", "collapsed": false, "input": [ "list1 = range(25)\n", "print(list1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]\n" ] } ], "prompt_number": 113 }, { "cell_type": "code", "collapsed": false, "input": [ "list2 = [list1[n] for n in list1 if n%2!=0] # This removes all even numbers\n", "print(list2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]\n" ] } ], "prompt_number": 112 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Booleans are just values tied to certain expressions that evaluate to either true or false. If and while statements are evaluated based on these values. For example, below we said 5 < 3 and the computer says False because that isn't true" ] }, { "cell_type": "code", "collapsed": false, "input": [ "5 < 3" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 117, "text": [ "False" ] } ], "prompt_number": 117 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The conditional statements that you should be most familiar with are \"if/elif/else\" and \"while\". They are used exactly how you would imagine that they are used. You want to tell the computer if something is true then do this, else do this other thing. You could also tell your computer while this condition is true then continue doing what I told you to do. Below are two examples (Note where the indentations (done by inserting 4 spaces) are):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 3\n", "if x < 3:\n", " print('x is less than 3')\n", "elif x < 4:\n", " print('x is less than 4')\n", "else:\n", " print('x is not less than 4')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "x is less than 4\n" ] } ], "prompt_number": 118 }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1\n", "while x < 7:\n", " print('x is still less than 7')\n", " x = x + 1 # Increase x by 1" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "x is still less than 7\n", "x is still less than 7\n", "x is still less than 7\n", "x is still less than 7\n", "x is still less than 7\n", "x is still less than 7\n" ] } ], "prompt_number": 115 }, { "cell_type": "markdown", "metadata": {}, "source": [ "For conditional statements, if you are asking whether something is equal you need to use two =. This is because python thinks one = means that you are setting something equal to that, but you are asking whether it is or isn't. See example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 6\n", "if x == 6:\n", " print('told ya so :)')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "told ya so :)\n" ] } ], "prompt_number": 124 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Looping is a very similar to a while loop, but you give it a specific number of times it should do something. For example if we had a list and we wanted to square every element, we could use a for loop." ] }, { "cell_type": "code", "collapsed": false, "input": [ "list1 = [1, 2, 3, 4, 5, 6]\n", "\n", "for i in range(len(list1)): # len(list1) tells us how many elements we need to loop on\n", " list1[i] = list1[i]**2 # The ith element of list1 = (ith element of list1) ^2\n", "\n", "print('list1 squared is %s' %list1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "list1 squared is [1, 4, 9, 16, 25, 36]\n" ] } ], "prompt_number": 121 }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Developing a Function and Exploring Modules" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Python Modules" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the biggest benefits of python is the fact that it is open source. This means that there are almost constanly individuals contributing to python to build modules. Modules are just files that contain python code that you are able to use. Some of the modules that you will use very frequently are: math, numpy, pandas, byumcl, and other modules you might write for yourself. Although you will use these most, if you ever think that something would be nice to be able to do then most likely someone has written a module that does that task. Once again, google will be your best friend in finding these.\n", "\n", "You need to import modules into your session to be able to use them. You need to do all of your imports at the very beginning when you are writing a script. These imports are done like this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import numpy as np # the 'as np' part creates a nickname for functions from this module\n", "import math\n", "import os\n", "from filename import * # will import functions that you have written in another script\n", "\n", "\"\"\"\n", "Here you would write the rest of your script\n", "\"\"\"\n", "\n", "x = math.pi" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 106 }, { "cell_type": "markdown", "metadata": {}, "source": [ "You have to refer to the module you just imported in order to call an object from that module. For example: We wrote math.pi in the code above. This tells python to look in the math module and call the function pi. When we write things like the \"import numpy as np\", we are giving numpy a nickname and we can write np.numpy_function instead of writing numpy.numpy_function. It is also helpful to try help(module) to see if you can find documentation. You can also use module.object? to open the documentation for a specific object in a module." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Defining Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although python provides you with many built in functions, sometimes you need to write functions that perform very specific actions. Luckily, python allows you to write your own functions. This is actually very simple. All you need to do is follow is give your function a name, ask for inputs, write the function, and return something. Indentation is important here as well. See example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def square(x): # We give the function the name square and say we pass in x\n", " '''\n", " Really pretty documentation that you should write all the time\n", "\n", " Parameters\n", " ----------\n", " ....\n", " \n", " Outputs\n", " -------\n", " ...\n", " '''\n", " \n", " output = x * x # define some variable that we will be the output of our function\n", " return output # return the variable output" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 125 }, { "cell_type": "code", "collapsed": false, "input": [ "square(45)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 126, "text": [ "2025" ] } ], "prompt_number": 126 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Writing Scripts and the Zen of Python" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Writing a Script" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Writing a script is pretty simple, so I will try and go over it pretty quick. A script should start with all of your imports and then you write your code. It should be neat and you should leave one clean line at the end of your script or the code monster will come and eat you. Example of a script:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import math\n", "import os\n", "from __future__ import division\n", "\n", "x = 2.0\n", "\n", "y = x * math.pi\n", "\n", "finalstuff = square(y)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 128 }, { "cell_type": "markdown", "metadata": {}, "source": [ "After you have written a script then you need to enter your ipython console. From there, direct your computer to the directory where the script is stored and type \"run script.py\" That's it for running scripts." ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Zen of Python (PEP 20)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The Zen of Python is a set of basic rules that one should follow when writing python code. They are important to follow as they will make your code readable and will bring good code karma to you and your family. Anytime that you forget these rules, type \"import this\" into your console.\n", "\n", "Beautiful is better than ugly.\n", "\n", "Explicit is better than implicit.\n", "\n", "Simple is better than complex.\n", "\n", "Complex is better than complicated.\n", "\n", "Flat is better than nested.\n", "\n", "Sparse is better than dense.\n", "\n", "Readability counts.\n", "\n", "Special cases aren't special enough to break the rules.\n", "\n", "Although practicality beats purity.\n", "\n", "Errors should never pass silently.\n", "\n", "Unless explicitly silenced.\n", "\n", "In the face of ambiguity, refuse the temptation to guess.\n", "\n", "There should be one-- and preferably only one --obvious way to do it.\n", "\n", "Although that way may not be obvious at first unless you're Dutch.\n", "\n", "Now is better than never.\n", "\n", "Although never is often better than *right* now.\n", "\n", "If the implementation is hard to explain, it's a bad idea.\n", "\n", "If the implementation is easy to explain, it may be a good idea.\n", "\n", "Namespaces are one honking great idea -- let's do more of those!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import this" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The Zen of Python, by Tim Peters\n", "\n", "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n", "Complex is better than complicated.\n", "Flat is better than nested.\n", "Sparse is better than dense.\n", "Readability counts.\n", "Special cases aren't special enough to break the rules.\n", "Although practicality beats purity.\n", "Errors should never pass silently.\n", "Unless explicitly silenced.\n", "In the face of ambiguity, refuse the temptation to guess.\n", "There should be one-- and preferably only one --obvious way to do it.\n", "Although that way may not be obvious at first unless you're Dutch.\n", "Now is better than never.\n", "Although never is often better than *right* now.\n", "If the implementation is hard to explain, it's a bad idea.\n", "If the implementation is easy to explain, it may be a good idea.\n", "Namespaces are one honking great idea -- let's do more of those!\n" ] } ], "prompt_number": 129 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Style Guide for Python (PEP 8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "PEP 8 is too long to put into this document, but I would highly suggest reading through it. The suggestions in PEP 8 are very helpful in making your code readable and in line with the Zen of Python. I will include a few of the tips that I find important.\n", "\n", "**Indentation**: Use 4 spaces per indentation level. Python's implicit line joining inside parentheses, brackets and braces, or using a hanging indent. When using a hanging indent the following considerations should be applied; there should be no arguments on the first line and further indentation should be used to clearly distinguish itself as a continuation line.\n", "\n", "**Maximum Line Length**: Limit all lines to a maximum of 79 characters.\n", "\n", "**Blank Lines**: Separate top-level function and class definitions with two blank lines. Method definitions inside a class are separated by a single blank line. Extra blank lines may be used (sparingly) to separate groups of related functions. Blank lines may be omitted between a bunch of related one-liners (e.g. a set of dummy implementations).\n", "\n", "**Whitespace in Expressions**: Avoid extraneous whitespace in the following situations: Immediately inside parentheses, brackets or braces; Immediately before a comma, semicolon, or colon, Immediately before the open parenthesis that starts the argument list of a function call, Immediately before the open parenthesis that starts an indexing or slicing, More than one space around an assignment (or other) operator to align it with another. If operators with different priorities are used, consider adding whitespace around the operators with the lowest priority(ies). Use your own judgement; however, never use more than one space, and always have the same amount of whitespace on both sides of a binary operator. For example:\n", "\n", "Yes" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 0\n", "x += 1\n", "x = x + 1\n", "x = x**2 + 2\n", "test = x*x + 2*x\n", "y = (x+2) * (x-3)" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 130 }, { "cell_type": "markdown", "metadata": {}, "source": [ "No" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x=x+1\n", "x +=1\n", "x = 2 * x + 1\n", "y = (x + 2) * (x - 3)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Comments**: Comments that contradict the code are worse than no comments. Always update comments! Comments should be complete sentences.\n", "\n", "We are hoping to edit your code and give you tips on how to make it stay consistent with PEP 8 and PEP 20. We recommend using the sublime_linter in Sublimetext 2 to stay in line with PEP 8." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Problems:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All scripts submitted should obviously be in line with PEP 8 and PEP 20 for this assignment because that is one of the topics covered. Include comments." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Problem 1**: Write a script that generates the following:\n", "\n", "i) A list with all of the elements from 0 to 100\n", "\n", "ii) A list with all of the even elements from 0 to 100\n", "\n", "iii) A list that contains all of the even numbers starting at 100 and going to 0\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Problem 2**: Write a script that creates a piecewise function f(x) = y that satisfies the following:\n", "\n", "i) When x < 0 then y = 0\n", "\n", "ii) When 0 <= x <=5 then y = x*x\n", "\n", "iii) When x > 5 then y = 25\n", "\n", "iv) Now copy the following code to create a plot" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import matplotlib.pyplot as plt\n", "# Define function in here\n", "test = range(-10, 15, 1)\n", "plt.plot(test, [f(i) for i in test]) # Note this isn't your actual function being plotted below.\n", "plt.show()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "pyout", "prompt_number": 132, "text": [ "[]" ] }, { "output_type": "display_data", "png": "iVBORw0KGgoAAAANSUhEUgAAAXoAAAD9CA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ia2Oyc2Hn2kjpLRDa2tpUWFio\ngoICZWVlaevWrbpw4UIql5CRTABfhbR69WrNnz9/1GM//vijduzYIUnasWOHfvjhh3QsLeUmOhdS\nMK+LV199VeXl5ZKkuXPnavny5erv7w/ktTHZuZBmf22kdND39/crPz8//nNeXl584UFlWZaqq6tV\nWVmpL7/8Mt3LSavBwUGFQiFJUigU0uDgYJpXlF5NTU0qKytTXV2dHjx4kO7lpFxvb686Ojr05ptv\nBv7aGDkXq1atkjT7ayOlg55fyo7366+/qqOjQ5cvX9bJkyd17dq1dC8pI1iWFejrZc+ePerp6VFn\nZ6dycnK0f//+dC8ppR49eqTNmzfr+PHjevnll0f9WdCujUePHundd9/V8ePHNXfuXFvXRkoH/djX\n2Pf19Skv4Pc9yMnJkSQtXLhQmzZtmvB2EUERCoXib9CLxWLKzs5O84rSJzs7Oz7Qdu3aFajrYmho\nSJs3b9b27du1ceNGScG9NkbOxfvvvx8/F3aujZQO+srKSt26dUu9vb16+vSpzp8/r5qamlQuIaM8\nefJEDx8+lCQ9fvxYV65cUWlpaZpXlT41NTVqbm6WJDU3N8cv7CCKxWLx71taWgJzXRhjVFdXp5KS\nEn388cfxx4N4bUx2LmxdGw7/onhaly5dMkVFRWbJkiWmoaEh1YfPKH/++acpKyszZWVlZsWKFYE6\nH1u3bjU5OTkmKyvL5OXlma+++srcvXvXrFmzJlAvoTNm/Lk4c+aM2b59uyktLTVvvPGG2bBhgxkY\nGEj3MlPi2rVrxrIsU1ZWNurlg0G8NiY6F5cuXbJ1bVjGBPBX+wAQIBn1CVMAAOcx6AHA5xj0AOBz\nDHoA8DkGPQD4HIMeAHzu/4RJ93opm/cIAAAAAElFTkSuQmCC\n" } ], "prompt_number": 132 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Problem 3**: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n", "\n", "Write a script that prints the sum of all the multiples of 3 or 5 below 1000." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }